{% extends "base.html" %}

{% block title %}预约管理 - 智慧医院资源调度系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">预约管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="exportAppointments()">导出</button>
        </div>
        <button type="button" class="btn btn-sm btn-primary" onclick="createAppointment()">
            <i class="fas fa-plus me-1"></i>新建预约
        </button>
    </div>
</div>

<!-- 筛选器 -->
<div class="row mb-4">
    <div class="col-md-3">
        <select class="form-select" id="statusFilter">
            <option value="">全部状态</option>
            <option value="pending">待确认</option>
            <option value="confirmed">已确认</option>
            <option value="completed">已完成</option>
            <option value="cancelled">已取消</option>
        </select>
    </div>
    <div class="col-md-3">
        <select class="form-select" id="departmentFilter">
            <option value="">全部科室</option>
            <option value="1">内科</option>
            <option value="2">外科</option>
            <option value="3">妇科</option>
            <option value="4">儿科</option>
        </select>
    </div>
    <div class="col-md-3">
        <input type="date" class="form-control" id="dateFilter" placeholder="选择日期">
    </div>
    <div class="col-md-3">
        <button type="button" class="btn btn-primary" onclick="filterAppointments()">
            <i class="fas fa-search me-1"></i>筛选
        </button>
    </div>
</div>

<!-- 预约列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">预约列表</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped" id="appointmentsTable">
                <thead>
                    <tr>
                        <th>预约ID</th>
                        <th>患者姓名</th>
                        <th>科室</th>
                        <th>预约类型</th>
                        <th>预约时间</th>
                        <th>状态</th>
                        <th>优先级</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 动态加载数据 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 预约详情模态框 -->
<div class="modal fade" id="appointmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">预约详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="appointmentDetails">
                <!-- 动态加载详情 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="confirmAppointment()">确认预约</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let appointments = [];

    // 页面加载时获取预约列表
    document.addEventListener('DOMContentLoaded', function() {
        loadAppointments();
    });

    // 加载预约列表
    async function loadAppointments() {
        try {
            const response = await fetch('/api/appointments', {
                headers: {
                    'Authorization': 'Bearer ' + getToken()
                }
            });
            const data = await response.json();
            
            if (response.ok) {
                appointments = data;
                renderAppointments(data);
            } else {
                showAlert('加载预约列表失败: ' + data.error, 'danger');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showAlert('网络请求失败', 'danger');
        }
    }

    // 渲染预约列表
    function renderAppointments(data) {
        const tbody = document.querySelector('#appointmentsTable tbody');
        tbody.innerHTML = '';
        
        data.forEach(appointment => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${appointment.id}</td>
                <td>${appointment.patient_name}</td>
                <td>${appointment.department_name}</td>
                <td>${appointment.appointment_type}</td>
                <td>${new Date(appointment.scheduled_time).toLocaleString()}</td>
                <td><span class="badge bg-${getStatusColor(appointment.status)}">${getStatusText(appointment.status)}</span></td>
                <td>${appointment.priority}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="viewAppointment(${appointment.id})">查看</button>
                    <button class="btn btn-sm btn-outline-success" onclick="confirmAppointment(${appointment.id})">确认</button>
                    <button class="btn btn-sm btn-outline-danger" onclick="cancelAppointment(${appointment.id})">取消</button>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 获取状态颜色
    function getStatusColor(status) {
        const colors = {
            'pending': 'warning',
            'confirmed': 'success',
            'completed': 'info',
            'cancelled': 'danger'
        };
        return colors[status] || 'secondary';
    }

    // 获取状态文本
    function getStatusText(status) {
        const texts = {
            'pending': '待确认',
            'confirmed': '已确认',
            'completed': '已完成',
            'cancelled': '已取消'
        };
        return texts[status] || status;
    }

    // 查看预约详情
    async function viewAppointment(appointmentId) {
        try {
            const response = await fetch(`/api/appointments/${appointmentId}`, {
                headers: {
                    'Authorization': 'Bearer ' + getToken()
                }
            });
            const data = await response.json();
            
            if (response.ok) {
                showAppointmentDetails(data);
            } else {
                showAlert('获取预约详情失败: ' + data.error, 'danger');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showAlert('网络请求失败', 'danger');
        }
    }

    // 显示预约详情
    function showAppointmentDetails(appointment) {
        const detailsDiv = document.getElementById('appointmentDetails');
        detailsDiv.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <h6>基本信息</h6>
                    <p><strong>预约ID:</strong> ${appointment.id}</p>
                    <p><strong>患者姓名:</strong> ${appointment.patient_name}</p>
                    <p><strong>科室:</strong> ${appointment.department_name}</p>
                    <p><strong>预约类型:</strong> ${appointment.appointment_type}</p>
                </div>
                <div class="col-md-6">
                    <h6>时间信息</h6>
                    <p><strong>预约时间:</strong> ${new Date(appointment.scheduled_time).toLocaleString()}</p>
                    <p><strong>持续时间:</strong> ${appointment.duration}分钟</p>
                    <p><strong>状态:</strong> <span class="badge bg-${getStatusColor(appointment.status)}">${getStatusText(appointment.status)}</span></p>
                    <p><strong>优先级:</strong> ${appointment.priority}</p>
                </div>
            </div>
            ${appointment.notes ? `<div class="mt-3"><h6>备注</h6><p>${appointment.notes}</p></div>` : ''}
            ${appointment.assignments && appointment.assignments.length > 0 ? `
                <div class="mt-3">
                    <h6>资源分配</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>资源名称</th>
                                    <th>开始时间</th>
                                    <th>结束时间</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${appointment.assignments.map(assignment => `
                                    <tr>
                                        <td>${assignment.resource_name}</td>
                                        <td>${new Date(assignment.start_time).toLocaleString()}</td>
                                        <td>${new Date(assignment.end_time).toLocaleString()}</td>
                                        <td><span class="badge bg-${getStatusColor(assignment.status)}">${getStatusText(assignment.status)}</span></td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            ` : ''}
        `;
        
        const modal = new bootstrap.Modal(document.getElementById('appointmentModal'));
        modal.show();
    }

    // 确认预约
    async function confirmAppointment(appointmentId) {
        if (!appointmentId) {
            showAlert('请选择要确认的预约', 'warning');
            return;
        }
        
        try {
            const response = await fetch(`/api/appointments/${appointmentId}/confirm`, {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + getToken(),
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.ok) {
                showAlert('预约确认成功', 'success');
                loadAppointments();
            } else {
                const data = await response.json();
                showAlert('确认预约失败: ' + data.error, 'danger');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showAlert('网络请求失败', 'danger');
        }
    }

    // 取消预约
    async function cancelAppointment(appointmentId) {
        if (!confirm('确定要取消这个预约吗？')) {
            return;
        }
        
        try {
            const response = await fetch(`/api/appointments/${appointmentId}/cancel`, {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + getToken(),
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.ok) {
                showAlert('预约已取消', 'success');
                loadAppointments();
            } else {
                const data = await response.json();
                showAlert('取消预约失败: ' + data.error, 'danger');
            }
        } catch (error) {
            console.error('请求失败:', error);
            showAlert('网络请求失败', 'danger');
        }
    }

    // 筛选预约
    function filterAppointments() {
        const status = document.getElementById('statusFilter').value;
        const department = document.getElementById('departmentFilter').value;
        const date = document.getElementById('dateFilter').value;
        
        let filtered = appointments;
        
        if (status) {
            filtered = filtered.filter(apt => apt.status === status);
        }
        
        if (department) {
            filtered = filtered.filter(apt => apt.department_id == department);
        }
        
        if (date) {
            const filterDate = new Date(date);
            filtered = filtered.filter(apt => {
                const aptDate = new Date(apt.scheduled_time);
                return aptDate.toDateString() === filterDate.toDateString();
            });
        }
        
        renderAppointments(filtered);
    }

    // 创建预约
    function createAppointment() {
        window.location.href = '/appointments/create';
    }

    // 导出预约
    function exportAppointments() {
        // 实现导出功能
        showAlert('导出功能开发中', 'info');
    }
</script>
{% endblock %}
